#pragma once

#include <functional>
#include <signal.h>
#include "Socket.hpp"

using func_t = std::function<std::string(std::string &package)>;

class TcpServer
{
public:
    TcpServer(uint16_t port, func_t callback)
        : port_(port), callback_(callback)
    {
    }

    bool InitServer()
    {
        listensock_.Socket();
        listensock_.Bind(port_);
        listensock_.Listen();
        lg(Info, "init server success...");
        return true;
    }
    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        while (true)
        {
            // 获取客户端的信息
            std::string clientip;
            uint16_t clientport;
            int sockfd = listensock_.Accept(clientip, clientport);
            if (sockfd < 0)
                continue;
            // 获取链接失败，我们就继续获取链接
            lg(Info, "accept a new link, sockfd: %d, clientip:%s, clientport:%d", sockfd, clientip.c_str(), clientport);
            // 提供服务--子进程提供
            if (fork() == 0)
            {
                listensock_.Close();
                std::string inbuffer_stream;
                // 数据计算
                while (true)
                {
                    char buffer[1280];
                    // 读取在网络当中的报文，对报文进行处理，在返回
                    //  对报文的处理：Calculater（）
                    ssize_t n = read(sockfd, buffer, sizeof(buffer));
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        inbuffer_stream += buffer;
                        lg(Debug, "debug: \n%s", inbuffer_stream.c_str());

                        while (true)
                        {
                            std::string info = callback_(inbuffer_stream);
                            if (info.empty())
                                continue;

                            // 在把处理好的数据以报文的形式发送到网络中
                            write(sockfd, info.c_str(), info.size());
                        }
                    }

                    else if (n == 0)
                        break;
                    else
                        break;
                }

                exit(0);
            }
            close(sockfd);
        }
    }
    ~TcpServer()
    {
    }

private:
    uint16_t port_;
    Sock listensock_;
    func_t callback_;
};